from flask import request, Flask
import time
import cv2
import numpy as np
import json
import base64
import paddlex as pdx

model = pdx.deploy.Predictor('E:/555/P0006-T0010_export_model/inference_model')
app = Flask(__name__)


@app.route("/", methods=['POST'])
def get_picture():
    start_time = time.time()
    upload_file = request.get_data()
    req = json.loads(upload_file)
    # old_file_name = upload_file.filename
    sign = {}

    if upload_file:
        name = req['name']
        t2 = time.time()
        print("[+]接收用时" + str(t2 - start_time) + ":" + name)
        img_str = req['image']  # 得到unicode的字符串
        threshold = req['threshold'] #得到阈值
        img_decode_ = img_str.encode('ascii')  # 从unicode变成ascii编码
        img_decode = base64.b64decode(img_decode_)  # 解base64编码，得图片的二进制
        img_np_ = np.frombuffer(img_decode, np.uint8)
        img = cv2.imdecode(img_np_, cv2.COLOR_RGB2BGR)  # 转为opencv格式
        img = img.astype('float32')
        t3 = time.time()
        print("[+]解码用时：" + str(t3 - t2))
        result = model.predict(img)
        if model.model_type == "detector":
            # threshold用于过滤低置信度目标框
            print(result)
            for item in range(len(result)):
                if result[item]['score'] >threshold:
                    data = {}
                    print('score:' + str(result[item]['score']))
                    print(type(result[item]['score']))

                    print(threshold)
                    print(type(threshold))

                    data['label'] = result[item]['category']
                    if result[item]['category'] == 'DY' or result[item]['category'] == 'WH':
                        data['x'] = int(result[item]['bbox'][0] + 0.5 * result[item]['bbox'][2] + 50)
                        data['y'] = int(result[item]['bbox'][1] + 0.5 * result[item]['bbox'][3])
                    else:
                        data['x'] = int(result[item]['bbox'][0] + 0.5*result[item]['bbox'][2])
                        data['y'] = int(result[item]['bbox'][1] + 0.5*result[item]['bbox'][3])

                    sign.update({item:data})


                else:
                    pass

            print('[+]识别用时：' + str(time.time() - t3))

        return sign
    else:
        return '[-]failed'






if __name__ == "__main__":
    app.run("127.0.0.1", port=24401)